import {View, ScrollView, Text, Textarea} from "@tarojs/components";
import {
  ActionSheet, ActionSheetItem,
  Button,
  Cell,
  CellGroup,
  Field,
  Radio,
  RadioGroup,
  Space, Stepper,
  Steps,Image
} from "@antmjs/vantui";
import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState} from "react";

import LogUtils from "@/utils/log";
import AssetImage from "@/common/AssetImage";
import Utils from "@/utils/common";
import RouthPath from "@/common/RouthPath";
import {
  KeyTitleModel,
  MachineModel,
  MachineProjectParams,
  ProjectModel,
  TeamModel, UserListModel
} from "@/common/apis/model";
import DateUtils from "@/utils/date_utils";
import StyleUtils from "@/utils/style_utils";
import {
  machineList2Api,
  orderSaveApi,
  orderTimeApi,
  projectMachineListApi,
  teamJoinApi
} from "@/common/apis/home_datasource";
import LocalData from "@/common/local_data";
import ShowUtils from "@/utils/show_utils";
import EventUtils from "@/utils/event_utils";
import TimeSelect2 from "@/components/time_select";
import './index.less'

definePageConfig({
  navigationBarTitleText: '项目预约'
})

interface ProjectBookApiParams {
  //样品页面
  getType?: any
  getType2?: any
  address?: string
  isRecycling?: any
  beiZhu?: any
  //项目页面
  machineId?: MachineModel
  projectId?: ProjectModel
  scheduleId?: KeyTitleModel
  user?: UserListModel
  price?: any
  num?: number
  //客户页面
  nickName?: any
  phone?: any
  groupId?: TeamModel
}

export default function ProjectBook() {

  const steps = useRef([

    {
      text: '项目信息',
      desc: '',
    },
    {
      text: '客户信息',
      desc: '',
    },
    {
      text: '样品信息',
      desc: '',
    }
  ])
  const childRef = useRef(null); // 仍然使用 useRef

  const [active, setActive] = useState(-1)

  const allData = useRef<ProjectBookApiParams>({});

  //设置值

  const OnSetResult = useCallback((value) => {
    allData.current = {...allData.current, ...value}
    LogUtils.error(allData.current, active)
    if (active < 2) {
      setActive(active + 1)
    } else {
      Utils.modal('确定预约', `确定预约`, true, (ok) => {
        if (!ok) {
          return;
        }
        const type = allData.current.machineId?.type
        //转成api需要的参数
        const params = {
          machineId: allData.current.machineId?.id,
          projectId: allData.current.projectId?.id,
          //可以不选
          bookAllTimes: allData.current.scheduleId ? DateUtils.formatDateTimeArray(allData.current.scheduleId.key) : '',
          contacts: allData.current.nickName,
          phone: allData.current.phone,
          //可以不选
          teamId: allData.current.groupId ? ShowUtils.getDefault(allData.current.groupId.id, '') : null,
          teamName: allData.current.groupId ? ShowUtils.getDefault(allData.current.groupId.name, '') : null,
          way: allData.current.getType ? allData.current.getType : '0',
          shootingWay: allData.current.getType2 ? allData.current.getType2 : '0',

          //可以不选
          recycleDetail: allData.current.address ? ShowUtils.getDefault(allData.current.address, '') : '',
          note: allData.current.beiZhu,
          recycle: allData.current.isRecycling ? allData.current.isRecycling : '1',
          amount: allData.current.price,
          actualAmount: allData.current.price,
          userId: allData.current.user?.id,
          userName: allData.current.user?.username,
          bookTotalTime: type === LocalData.notTimeId ? allData.current.num ?? 1 : allData.current.scheduleId ? allData.current.scheduleId.key.length / 2 : ''
        }
        //需要处理id
        orderSaveApi(params).then((res) => {
          if (res) {
            Utils.showOkToast('预约成功')
            Utils.navigateBack({
              delta: 2 // Go back one page
            })
          } else {
            Utils.showErrorToast('预约失败')
          }
        })
      })
    }
  }, [active]);

  useEffect(() => {
    const params = Utils.getParamsByRouter(Utils.getI())
    if (params && params.data) {
      const p = Utils.getObjectWithUrl<MachineProjectParams>(params.data)
      allData.current = {
        projectId: p.projectId,
        machineId: p.machineId,
        price: p.machineId.type === LocalData.notTimeId ? p.projectId.price : undefined
      }
      LogUtils.info(allData.current)
    }
    setActive(0)
  }, []);

  return (
    <View style={{
      display: 'flex',
      flexDirection: 'column',
      height: '100VH',

      boxSizing: 'border-box'
    }}
    >
      <View style={{
        zIndex: 0,
      }}
      > <Steps steps={steps.current} active={active} activeIcon='success' activeColor='#38f'
        style={{margin: '20px'}}
      /></View>
      <View style={{flex: 1, position: 'relative', overflow: 'hidden'}}>
        <ScrollView scrollY style={{height: '100%', boxSizing: 'border-box'}}>
          {active === 0 ? <ProjectInfo ref={childRef} OnSetResult={OnSetResult} initialData={allData.current} /> : null}
          {active === 1 ? <UserInfo ref={childRef} OnSetResult={OnSetResult} initialData={allData.current} /> : null}
          {active === 2 ? <SampleInfo ref={childRef} OnSetResult={OnSetResult} initialData={allData.current} /> : null}
        </ScrollView>
      </View>
      <View style={{display: 'flex', justifyContent: 'flex-end', marginRight: '20PX'}}>
        <Space>
          <Button type='info' disabled={active === 0} plain hairline onClick={() => {
            if (active > 0) {
              setActive(active - 1)
            }
          }}
          >
            上一步
          </Button>
          <Button type='info' onClick={() => {
            if (childRef.current) {
              childRef.current.handleSubmit();
            }
          }}
          >
            下一步
          </Button>

        </Space>
      </View>
    </View>
  )
}

interface UserInfoProps {
  OnSetResult: (value: any) => void;
  initialData: Record<string, any>; // Receive initial data
}

interface UserInfoModel {
  nickName?: any
  phone?: any
  groupId?: TeamModel
}


const UserInfo = forwardRef<any, UserInfoProps>(({OnSetResult, initialData}, ref) => {

  const [fieldValues, setFieldValues] = useState<UserInfoModel>({})

  const handleSubmit = () => {
    LogUtils.info(fieldValues)
    if (fieldValues) {
      if (!Utils.isNotBlank(fieldValues.nickName)) {
        Utils.showErrorToast('客户姓名不能为空')
        return;
      }
      if (!Utils.isMobilePhone(fieldValues.phone)) {
        Utils.showErrorToast('客户电话格式不对')
        return;
      }
    }
    OnSetResult(fieldValues); // Use the prop function name
  };

  useImperativeHandle(ref, () => ({
    handleSubmit: handleSubmit
  }));
  useEffect(() => {
    setFieldValues({
      nickName: initialData.nickName,
      phone: initialData.phone,
      groupId: initialData.groupId,
    })
  }, [initialData]);

  const handleGroupSelect = (e: any) => {
    setFieldValues(prev => ({
      ...prev,
      groupId: e.detail
    }));
    setShow(false)
  }

  const inputChange = useCallback((e, type) => {
    //修改值
    setFieldValues((prevValues) => {
      const newValues = {...prevValues};
      if (type === "0") {
        newValues.nickName = e;
      } else if (type === "1") {
        newValues.phone = e;
      }
      return newValues;
    });

  }, []);
  const [show, setShow] = useState(false)

  const [, setRefresh] = useState({})

  const actions = useRef<ActionSheetItem[]>()
  useEffect(() => {
    teamJoinApi(initialData.user.id).then((res) => {
      actions.current = res;
      setRefresh({})
    })
  }, []);
  return (
    <View style={{width: '100%', display: 'flex', flexDirection: 'column', '--cell-group-title-color': 'black'}}>
      <CellGroup title='客户信息'>
        <Cell title='客户姓名' required />
        <View style={{padding: '0 20px 20px 10px', boxSizing: 'border-box'}}>
          <Field
            style={{
              backgroundColor: AssetImage.bg,
            }}
            value={fieldValues ? fieldValues.nickName : ''}
            placeholder='请输入客户姓名'
            onInput={(e) => inputChange(e.detail, "0")}
            border={false}
          />
        </View>
        <Cell title='客户电话' required />
        <View style={{padding: '0 20px 20px 10px', boxSizing: 'border-box'}}>
          <Field
            style={{
              backgroundColor: AssetImage.bg,
            }}
            value={fieldValues ? fieldValues.phone : ''}
            placeholder='请输入客户电话'
            type='number'
            onInput={(e) => inputChange(e.detail, "1")}
            border={false}
          />
        </View>
        {
          !Utils.isEmpty(actions.current) ? <Cell
            renderIcon={<Text style={{marginRight: '20px'}}>请选择团队</Text>}
            renderTitle={<Text
              style={StyleUtils.getMaxLines(2, {
                paddingLeft: '20px',
                color: !fieldValues.groupId ? AssetImage.gray2 : 'black',
                textAlign: 'right'
              })}
            >{fieldValues.groupId ? fieldValues.groupId.name : '请选择'}</Text>}
            onClick={() => {
              setShow(true)
            }}
            isLink
          /> : null
        }
      </CellGroup>
      <ActionSheet
        show={show}
        actions={actions.current}
        onClose={() => setShow(false)}
        onSelect={(e) => handleGroupSelect(e)}
      />
    </View>
  );
});

interface SampleInfoProps {
  OnSetResult: (value: any) => void;
  initialData: Record<string, any>; // Receive initial data
}

interface SampleInfoModel {
  getType?: any
  getType2?: any
  address?: String
  isRecycling?: any
  beiZhu?: any
}

const SampleInfo = forwardRef<any, SampleInfoProps>(({OnSetResult, initialData}, ref) => {
  // The 'ref' argument is ignored here!


  const [fieldValues, setFieldValues] = useState<SampleInfoModel>({})


  const options = useRef(LocalData.way);
  const options3 = useRef(LocalData.way2);

  const options2 = useRef(LocalData.recycle);
  useEffect(() => {
    setFieldValues({
      getType: initialData.getType,
      getType2: initialData.getType2,
      isRecycling: initialData.isRecycling,
      address: initialData.address,
      beiZhu: initialData.beiZhu
    })
  }, [initialData]);
  const handleSubmit = () => {
    OnSetResult(fieldValues); //
  };

  useImperativeHandle(ref, () => ({
    handleSubmit: handleSubmit
  }));

  const radioChange = useCallback((e, type) => {
    //修改值
    setFieldValues((prevValues) => {
      LogUtils.info(e)
      const newValues = {...prevValues};
      if (type === "0") {
        newValues.getType = e.detail;
      }else if (type === "4") {
        newValues.getType2 = e.detail;
      }  else if (type === "1") {
        newValues.isRecycling = e.detail;
      } else if (type === "3") {
        newValues.address = e;
      } else {
        newValues.beiZhu = e;
      }
      return newValues;
    });

  }, []);


  return (
    <View style={{width: '100%', display: 'flex', flexDirection: 'column', '--cell-group-title-color': 'black'}}>
      <CellGroup title='样品信息'>
        <Cell required renderTitle={<View style={{marginLeft: '20px'}}><RadioGroup
          value={fieldValues.getType2 ? fieldValues.getType2 : options3.current[0].value}
          onChange={(e) => radioChange(e, "4")}
          direction='horizontal'
          style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
        >   {options3.current.map((option) => (
          <Radio
            key={option.value}
            name={String(option.value)}
            shape='square'
          >
            {option.label}
          </Radio>
        ))}
        </RadioGroup></View>} renderIcon={<Text>拍摄方式</Text>}
        />


        <Cell required renderTitle={<View style={{marginLeft: '20px'}}><RadioGroup
          value={fieldValues.getType ? fieldValues.getType : options.current[0].value}
          onChange={(e) => radioChange(e, "0")}
          direction='horizontal'
          style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
        >   {options.current.map((option) => (
          <Radio
            key={option.value}
            name={String(option.value)}
            shape='square'
          >
            {option.label}
          </Radio>
        ))}
        </RadioGroup></View>} renderIcon={<Text>取样方式</Text>}
        />
        {
          fieldValues.getType === "1" ? <Cell required
            renderTitle={<Text
              style={{
                                                  display: 'inline-block',
                                                  marginLeft: '20px'
                                                }}
            >{LocalData.acceptAddress}</Text>}
            renderExtra={<Image src={AssetImage.copy}
              style={{width: '24px', height: '24px'}}
            />}
            renderIcon={<Text>邮寄地址</Text>}
            onClick={() => {
                                                Utils.copyToClipboard()
                                              }}
          />
            : null

        }


        <Cell required renderTitle={<View style={{marginLeft: '20px'}}><RadioGroup
          value={fieldValues.isRecycling ? fieldValues.isRecycling : options2.current[1].value}
          onChange={(e) => radioChange(e, "1")}
          direction='horizontal'
          style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
        >   {options2.current.map((option) => (
          <Radio
            key={option.value}
            name={String(option.value)}
            shape='square'
          >
            {option.label}
          </Radio>
        ))}
        </RadioGroup></View>} renderIcon={<Text>是否回收</Text>}
        />
        {
          fieldValues.isRecycling === "0" ? <CellGroup title='取样地址' border={false}>
            <View style={{margin: '0 20px'}}>
              <Textarea
                className='taro-textarea' // 给 Textarea 一个自定义类名方便样式控制
                style={{
                  // 如果 AssetImage.bg 是想应用在输入框本身，则放在这里
                  backgroundColor: AssetImage.bg,
                  minHeight: '50px', // 对应 autosize.minHeight
                  maxHeight: '50px', // 对应 autosize.maxHeight
                  width: '100%', // 通常 Textarea 需要占满父容器宽度
                  padding: '10px', // 内边距
                  boxSizing: 'border-box', // 推荐，使得 padding 和 border 不会增加元素的总宽高
                  fontSize: '14px', // 字体大小
                }}
                value={fieldValues.address}
                placeholder='请输入取样地址'
                onInput={(e) => radioChange(e.detail.value, "3")} // Taro Textarea 的事件是 onInput，detail 中是 value
              />
            </View>
          </CellGroup> : null
        }
        <CellGroup title='备注信息' border={false}>
          <View style={{padding: '0 20px'}}>
            <Textarea
              className='taro-textarea'
              style={{
                backgroundColor: AssetImage.bg,
                minHeight: '150px', // 对应 autosize.minHeight
                maxHeight: '150px', // 对应 autosize.maxHeight
                width: '100%', // 通常 Textarea 需要占满父容器宽度
                padding: '10px', // 内边距
                boxSizing: 'border-box', // 推荐，使得 padding 和 border 不会增加元素的总宽高
                fontSize: '14px', // 字体大小
              }}
              value={fieldValues.beiZhu}
              placeholder='请输入备注信息'
              onInput={(e) => radioChange(e.detail.value, "2")} // Taro Textarea 的事件是 onInput，detail 中是 value
            />
          </View>
        </CellGroup>
      </CellGroup>
    </View>
  )
});


interface ProjectInfoModel {
  machineId?: MachineModel
  projectId?: ProjectModel
  scheduleId?: KeyTitleModel
  user?: UserListModel
  num?: number
  price: any
}


interface ProjectInfoProps {
  OnSetResult: (value: Partial<ProjectInfoModel>) => void;
  initialData: Partial<ProjectInfoModel>; // Receive initial data
}

const ProjectInfo = forwardRef<any, ProjectInfoProps>(({OnSetResult, initialData}, ref) => {

  const [result, setResult] = useState<ProjectInfoModel>(() => {
    return {
      machineId: initialData.machineId || undefined,
      projectId: initialData.projectId || undefined,
      scheduleId: initialData.scheduleId || undefined,
      user: initialData.user || undefined,
      num: initialData.num || undefined,
      price: initialData.price || undefined,
    };
  });

  const handleSubmit = () => {
    if (!result.user || !result.projectId || !result.machineId) {
      Utils.showErrorToast('请完善项目信息');
      return;
    }
    if (result.machineId.type === LocalData.notTimeId || result.scheduleId) {
      OnSetResult(result);
    } else {
      Utils.showErrorToast('请完善项目信息');
    }
  };
  useImperativeHandle(ref, () => ({
    handleSubmit: handleSubmit
  }));
  const [showProject, setShowProject] = useState(false)
  const [showMachine, setShowMachine] = useState(false)
  //机器列表
  const machineList = useRef<MachineModel[]>([])

  const getMachineList = useCallback(() => {
    machineList2Api().then(res => {
      if (res) {
        machineList.current = res
      }
    })
  }, []);
  const handleMachineSelect = (e) => {
    if (result.machineId?.id === e.detail.id) {
      return
    }
    // --- Update state using setResult ---
    setResult(prev => ({
      ...prev,
      machineId: e.detail,
      // Assuming e.detail is the value for single column Picker
      projectId: undefined, // Adjust based on actual e.detail structure
      scheduleId: undefined, // Reset schedule
      num: 1,
      price: undefined,     // Reset price
    }));
    setShowMachine(false)
    getProjects(e.detail.id)
    if (e.detail.type !== LocalData.notTimeId) {
      getProjectTimes(e.detail.id)
    }
  }


  const handleUserSelect = (user) => {
    // --- Update state using setResult ---
    setResult(prev => ({
      ...prev,
      user: user,
    }));
  }
  const projects = useRef<ProjectModel[]>([])

  const getProjects = useCallback((id) => {
    projectMachineListApi(id, true).then(res => {
      if (res) {
        LogUtils.info(res)
        //把res content 拼接成name(note)
        res.forEach(item => {
          item.subname = item.note
        })
        projects.current = res
      }
    })
  }, []);


  const [availability, setAvailability] = useState<string>()
  const getProjectTimes = useCallback((id) => {
    orderTimeApi(id).then((data) => {
      if (data) {
        LogUtils.info(data)
        setAvailability(data.length > 0 ? data.join(",") : '')
      }
    })
  }, []);

  const handleProjectSelect = (e: any) => {
    //如果项目id一样就不更新
    if (result.projectId?.id === e.detail.id) {
      return
    }
    setResult(prev => ({
      ...prev,
      // Assuming e.detail is the value for single column Picker
      projectId: e.detail, // Adjust based on actual e.detail structure
      scheduleId: undefined, // Reset schedule
      price: prev.machineId?.type === LocalData.notTimeId ? getPrice(1, e.detail.price) : undefined,     // Reset price
    }));
    setShowProject(false)
  }
  const handleBeforeTimeSelectOpen = useCallback(() => {
    if (!result.machineId) {
      Utils.showErrorToast('请先选择机器');
      return false; // Prevent opening
    }
    if (!result.projectId) {
      Utils.showErrorToast('请先选择项目');
      return false; // Prevent opening
    }
    // Add any other conditions if needed
    return true; // All
  }, [result.machineId, result.projectId]);


  const getPrice = useCallback((num, price) => {
    //  price * num
    const totalPrice = price * num;
    return totalPrice.toFixed(2)
  }, []);


  const handleNumChange = useCallback((e) => {
    const number2 = e.detail
    setResult(prev => ({
      ...prev,
      num: number2, // Reset schedule
      price: getPrice(number2, prev.projectId?.price),     // Reset price
    }));
  }, [getPrice]);

  const selectTimes = useCallback((ids: any) => {
    if (ids.length > 0) {
      const showTimes = DateUtils.convertSlotIdToDescription(ids[0])
      setResult(prev => ({
        ...prev,
        scheduleId: {
          key: ids,
          title: `${showTimes} 共${ids.length / 2}小时`
        },
        price: getPrice(ids.length / 2, prev.projectId?.price) // Or calculate based on ids/logic
      }));
    }

  }, [getPrice]); // Dependencies might be needed if logic uses external vars


  useEffect(() => {
    if (result.machineId) {
      getProjects(result.machineId.id)
      if (result.machineId.type !== LocalData.notTimeId) {
        getProjectTimes(result.machineId.id)
      }
    }
    getMachineList()
  }, []);



  const renderTimeOrStep = useCallback((type) => {
    if (type == 0) {
      return (
        <Cell renderIcon={<Text>样品数量</Text>}
          renderTitle={<View style={{
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                '--stepper-input-disabled-text-color': 'black',
              }}
          ><Stepper
            value={result.num} integer disableInput onChange={(e) => {
                handleNumChange(e)
              }} disabled={!(result.machineId && result.projectId)}
          /></View>}
        />)
    } else {
      return (<TimeSelect2
        onBeforeOpen={handleBeforeTimeSelectOpen}
        items={DateUtils.getSelectTimes(availability ?? '')} max={100}
        onComplete={(values2) => {
            selectTimes(values2);
          }}
        initValues={result.scheduleId?.key ?? []}
        renderTitle={<Text
          style={StyleUtils.getMaxLines(2, {
              paddingLeft: '20px',
              color: !result.scheduleId ? AssetImage.gray2 : 'black',
              textAlign: 'right'
            })}
        >{result.scheduleId ? result.scheduleId.title : '请选择'}</Text>}
      />
      )
    }
  }, [availability, handleNumChange, result.machineId, result.num, result.projectId, result.scheduleId, selectTimes]);



  return (
    <View>
      <CellGroup title='项目信息'>
        {/* Use state value for display and color check */}
        <Cell
          renderIcon={<Text style={{marginRight: '20px'}}>请选择预约用户</Text>}
          renderTitle={<Text
            style={StyleUtils.getMaxLines(2, {
              paddingLeft: '20px',
              color: !result.user ? AssetImage.gray2 : 'black',
              textAlign: 'right'
            })}
          >{result.user ? `${result.user.username}(${result.user.mobile})` : '请选择'}</Text>}
          onClick={() => {
            Utils.navigateAndListenToEvent(RouthPath.userList, EventUtils.UserList, (data) => {
              handleUserSelect(data)
            })
          }}
          isLink
        />
        <Cell
          renderIcon={<Text style={{marginRight: '20px'}}>请选择机器</Text>}
          renderTitle={<Text
            style={StyleUtils.getMaxLines(2, {
              paddingLeft: '20px',
              color: !result.machineId ? AssetImage.gray2 : 'black',
              textAlign: 'right'
            })}
          >{result.machineId ? result.machineId.name : '请选择'}</Text>}
          onClick={() => {
            setShowMachine(true)
          }}
          isLink
        />
        <Cell
          renderIcon={<Text style={{marginRight: '20px'}}>请选择项目</Text>}
          renderTitle={<View style={{display: 'flex', flexDirection: 'row', justifyContent: 'flex-end'}}>
            <Text
              style={StyleUtils.getMaxLines(2, {
                paddingLeft: '20px',
                color: !result.machineId ? AssetImage.gray2 : 'black',
                textAlign: 'right'
              })}
            >{result.projectId ? `${result.projectId.name}` : '请选择'}</Text>
            {
              result.projectId && result.projectId.note ?
                <Text style={{color: 'red'}}>{ShowUtils.getShowNote(result.projectId.note)}</Text> : null
            }
          </View>}
          onClick={() => {
            if (!result.machineId) {
              Utils.showErrorToast('请选择机器');
              return;
            }
            setShowProject(true)
          }}
          isLink
        />
        {/* Pass state value */}
        {
          renderTimeOrStep(result.machineId?.type)
        }
        {/* Use state value for display and color check */}
        <View style={{'--cell-value-color': Utils.isThanZero(result.price) ? 'red' : AssetImage.gray2}}>
          <Cell title='价格' value={ShowUtils.getDefaultPrice(result.price ? result.price : '0')} />
        </View>
      </CellGroup>

      <ActionSheet
        show={showProject}
        key='id'
        actions={projects.current}
        onClose={() => setShowProject(false)}
        onSelect={(e) => handleProjectSelect(e)}
      />

      <ActionSheet
        show={showMachine}
        actions={machineList.current}
        onClose={() => setShowMachine(false)}
        onSelect={(e) => handleMachineSelect(e)}
      />
    </View>
  )
});



